package com.xinyi.share.weixin.utils;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.xinyi.share.weixin.message.Message;
import com.xinyi.share.weixin.message.MessageFactory;

/**
 * 
 * @ClassName: MessageUtils
 * @Description: 消息工具类
 * @author wangchuan
 * @date 2014年8月19日 下午12:13:16
 *
 */
public final class MessageUtils {
	private static final Logger logger = Logger.getLogger(MessageUtils.class);

	/**
	 * 格式化xml
	 * 
	 * @param xml
	 * @return
	 */
	public static Message formatXml(String xml) {
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(new ByteArrayInputStream(xml.getBytes("utf-8")));
			Element root = document.getRootElement();
			return MessageFactory.getReceiveMessage(root);
		} catch (DocumentException e) {
			logger.error("解析XML失败", e);
		} catch (UnsupportedEncodingException e) {
			logger.error("解析XML失败", e);
		}
		return null;
	}

	/**
	 * 
	 * @Title: groupPostString
	 * @Description: 分组POST数据组装
	 * @param id
	 * @param name
	 * @return
	 * @return String
	 * @throws
	 */
	public static String groupPostString(String id, String name) {
		StringBuilder jsonBuilder = new StringBuilder("{");
		jsonBuilder.append("\"").append("group").append("\":").append("{");
		if (StringUtils.isNotEmpty(id))
			jsonBuilder.append("\"").append("name").append("\"").append("=").append("\"").append(name).append("\"").append(",");
		jsonBuilder.append("\"").append("name").append("\"").append("=").append("\"").append(name).append("\"").append("}").append("}");
		return jsonBuilder.toString();
	}
}
